// src/main/java/mr/ali/webvideo/service/impl/WeChatPayService.java
package mr.ali.webvideo.service.impl;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import mr.ali.webvideo.model.WeChatPayRequest;
import mr.ali.webvideo.model.WeChatPayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeChatPayService {

    @Autowired
    private WXPay wxPay;

    @Value("${wechat.appid}")
    private String appId;

    @Value("${wechat.mchId}")
    private String mchId;

    @Value("${wechat.key}")
    private String key;

    /**
     * 创建微信支付订单
     * @param request 支付请求参数
     * @return 支付响应参数
     */
    public WeChatPayResponse createPayment(WeChatPayRequest request) throws Exception {
        // 构造统一下单参数
        Map<String, String> requestData = new HashMap<>();
        requestData.put("appid", appId);
        requestData.put("mch_id", mchId);  // 直接使用注入的商户ID
        requestData.put("nonce_str", WXPayUtil.generateNonceStr());
        requestData.put("body", request.getBody());
        requestData.put("out_trade_no", request.getOutTradeNo());
        requestData.put("total_fee", String.valueOf(request.getTotalFee()));
        requestData.put("spbill_create_ip", request.getSpbillCreateIp());
        requestData.put("notify_url", request.getNotifyUrl());
        requestData.put("trade_type", "JSAPI");
        requestData.put("openid", request.getOpenid());

        // 签名并调用微信统一下单接口
        String sign = WXPayUtil.generateSignature(requestData, key);
        requestData.put("sign", sign);

        Map<String, String> responseMap = wxPay.unifiedOrder(requestData);

        // 检查返回结果
        if (!"SUCCESS".equals(responseMap.get("return_code"))) {
            throw new RuntimeException("微信统一下单失败: " + responseMap.get("return_msg"));
        }

        if (!"SUCCESS".equals(responseMap.get("result_code"))) {
            throw new RuntimeException("微信统一下单失败: " + responseMap.get("err_code_des"));
        }

        // 构造前端支付参数
        WeChatPayResponse payResponse = new WeChatPayResponse();
        payResponse.setAppId(appId);
        payResponse.setTimeStamp(String.valueOf(System.currentTimeMillis() / 1000));
        payResponse.setNonceStr(WXPayUtil.generateNonceStr());
        payResponse.setPackageValue("prepay_id=" + responseMap.get("prepay_id"));
        payResponse.setSignType("MD5");

        // 生成支付签名
        Map<String, String> signParams = new HashMap<>();
        signParams.put("appId", appId);
        signParams.put("timeStamp", payResponse.getTimeStamp());
        signParams.put("nonceStr", payResponse.getNonceStr());
        signParams.put("package", payResponse.getPackageValue());
        signParams.put("signType", payResponse.getSignType());

        String paySign = WXPayUtil.generateSignature(signParams, key);
        payResponse.setPaySign(paySign);

        return payResponse;
    }

    /**
     * 处理微信支付回调通知
     * @param notifyData 通知数据
     * @return 处理结果
     */
    public String handleNotify(String notifyData) throws Exception {
        try {
            // 验证签名
            if (WXPayUtil.isSignatureValid(notifyData, key)) {
                Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);

                // 检查支付结果
                if ("SUCCESS".equals(notifyMap.get("return_code")) &&
                    "SUCCESS".equals(notifyMap.get("result_code"))) {

                    String outTradeNo = notifyMap.get("out_trade_no");
                    String transactionId = notifyMap.get("transaction_id");

                    // TODO: 处理支付成功逻辑，如更新订单状态等
                    log.info("支付成功，商户订单号: {}，微信支付订单号: {}", outTradeNo, transactionId);

                    // 返回成功响应
                    Map<String, String> response = new HashMap<>();
                    response.put("return_code", "SUCCESS");
                    response.put("return_msg", "OK");
                    return WXPayUtil.mapToXml(response);
                }
            }
        } catch (Exception e) {
            log.error("处理微信支付回调异常", e);
        }

        // 返回失败响应
        Map<String, String> response = new HashMap<>();
        response.put("return_code", "FAIL");
        response.put("return_msg", "FAIL");
        return WXPayUtil.mapToXml(response);
    }
}
